package cn.wolfcode.web.advice;

import cn.wolfcode.exception.BusinessException;
import cn.wolfcode.qo.JsonResult;
import com.alibaba.fastjson.JSON;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.method.HandlerMethod;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@ControllerAdvice()
public class ExceptionControllerAdvice {

    @ExceptionHandler(BusinessException.class)
    public void handleBusinessException(BusinessException e, HttpServletResponse response, HandlerMethod handlerMethod) throws IOException {
        e.printStackTrace();
        ResponseBody responseBody = handlerMethod.getMethodAnnotation(ResponseBody.class);
        if (responseBody==null){
            response.sendRedirect("/msgError");
        }else {
            response.setContentType("application/json;charset=utf-8");
            String string = JSON.toJSONString(new JsonResult(false, e.getMessage()));
            response.getWriter().write(string);
        }
    }

  /*  @ExceptionHandler(Exception.class)
    public void handleException(Exception e, HttpServletResponse response, HandlerMethod handlerMethod) throws IOException {
        e.printStackTrace();
        ResponseBody responseBody = handlerMethod.getMethodAnnotation(ResponseBody.class);
        if (responseBody==null){
            response.sendRedirect("/msgError");
        }else {
            response.setContentType("application/json;charset=utf-8");
            String string = JSON.toJSONString(new JsonResult(false, "系统错误"));
            response.getWriter().write(string);
        }
    }*/
}
